import {
  DEF_SHARE_INFO,
} from '@utils/default_config'
/**
 * 与app的交互
 * @param {fun} callback 
 */
function setupWebViewJavascriptBridge(callback) {
  if (window.WebViewJavascriptBridge) {
    return callback(WebViewJavascriptBridge);
  }
  if (window.WVJBCallbacks) {
    return window.WVJBCallbacks.push(callback);
  }
  window.WVJBCallbacks = [callback];
  var WVJBIframe = document.createElement('iframe');
  WVJBIframe.style.display = 'none';
  WVJBIframe.src = 'https://__bridge_loaded__';
  document.documentElement.appendChild(WVJBIframe);
  setTimeout(function() {
    document.documentElement.removeChild(WVJBIframe)
  }, 0)
}

/**
 * 退出
 */
export function appLogout() {
  setupWebViewJavascriptBridge(function(bridge) {
    // NOTE: 安卓调试
    try {
      // //初始化
      // bridge.init(function(data, responseCallback) {
      //   alert("bridge.init");
      //   responseCallback(data);
      // });
      // //Android调用js方法：functionInJs方法名称需要保持一致 ，并返回给Android通知
      // bridge.registerHandler("appLogout_register", function(data, responseCallback) {
      //   alert("bridge.registerHandler appLogout");
      //   var responseData = "我是Android调用js方法返回的数据---";
      //   responseCallback(responseData);
      // });
    } catch (e) {
      alert('error')
    }

    bridge.callHandler('appLogout', {}, function responseCallback(responseData) {})
  })
}

/**
 * 分享
 */
// export function appShare(param = {}, callback = null) {
//   setupWebViewJavascriptBridge(function(bridge) {
//     bridge.callHandler('appShare', param, function responseCallback(responseData) {
//       callback && callback(responseData)
//     })
//   })
// }

/**
 * 分享：APP端分享，传值给app
 */
export function appShareInfo(param = {}, callback = null) {
  param = Object.assign(DEF_SHARE_INFO, param)
  setupWebViewJavascriptBridge(function(bridge) {
    bridge.callHandler('appShareInfo', param, function responseCallback(responseData) {
      callback && callback(responseData)
    })
  })
}

/**
 * 支付
 */
export function appPay(param = {}, callback = null) {
  setupWebViewJavascriptBridge(function(bridge) {
    bridge.callHandler('appPay', param, function responseCallback(responseData) {
      callback && callback(responseData)
    })
  })
}